package com.hanhai.zrb.api.biz.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hanhai.common.bizInterface.ChangeNotifyUtil;
import com.hanhai.zrb.api.biz.dao.mybatis.FundMapper;
import com.hanhai.zrb.api.biz.dao.mybatis.PhotoDao;
import com.hanhai.zrb.api.biz.dao.mybatis.UserDao;
import com.hanhai.zrb.api.biz.dao.mybatis.UserStatisticDetailMapper;
import com.hanhai.zrb.api.biz.service.BizMonitorService;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.IntentionService;
import com.hanhai.zrb.api.biz.service.MessageSendService;
import com.hanhai.zrb.api.biz.service.ResourceMatchCacheManager;
import com.hanhai.zrb.api.biz.service.SysDictionaryService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.api.mongodb.SpringContextUtil;
import com.hanhai.zrb.api.solr.SolrHelper;
import com.hanhai.zrb.api.solr.SolrService;
import com.hanhai.zrb.model.common.SysDictionary;
import com.hanhai.zrb.model.fund.Fund;
import com.hanhai.zrb.model.fund.dto.FundDto;
import com.hanhai.zrb.model.fund.dto.FundSearchDto;
import com.hanhai.zrb.model.fund.vo.FundSearchVo;
import com.hanhai.zrb.model.intention.Intention;
import com.hanhai.zrb.model.photo.Photo;
import com.hanhai.zrb.model.photo.PhotoFundVo;
import com.hanhai.zrb.model.project.CityInfo;
import com.hanhai.zrb.model.project.Industry;
import com.hanhai.zrb.model.project.enums.ProjectStatusEnums;
import com.hanhai.zrb.model.resourcematch.ResourceMatchTypeEnum;
import com.hanhai.zrb.model.user.User;



@Service("fundService")
public class FundServiceImpl implements FundService{

	@Resource
	private FundMapper fundMapper;
	@Resource
	private SolrService solrService;
	@Resource
	private MessageSendService messageSendService;
    @Resource
    private IntentionService intentionService;
    @Resource
    private UserService userService;
    @Resource
    private IndustryService industryService;
    @Resource
    private CityInfoService cityInfoService;
    @Resource
    private SysDictionaryService sysDictionaryService;
	@Resource
	private UserStatisticDetailMapper userStatisticDetailMapper;
	@Autowired
	private UserDao userDao;
	@Autowired
	private PhotoDao photoDao;
	@Resource
	private ResourceMatchCacheManager resourceMatchCacheManager;
	private Logger logger = Logger.getLogger(getClass());
	/**
	 * 如果项目认证状态变化，就发出通知，监听此事件的对象能够出发通知
	 * @param projectId
	 */
	private void fundStatusNotify(Long fundId) {
		ChangeNotifyUtil.notify(FundService.notifySubject_change_authstatus,fundId);
	}

	@Override
	public Map<Long,Fund> queryByIdList(List<Long> list) {
		Map<Long,Fund> map =  new HashMap<Long,Fund>();
		if(CollectionUtils.isEmpty(list)){
			return map;
		}
		List<Fund> fundList = fundMapper.queryByIdList(list);
		if(CollectionUtils.isNotEmpty(fundList)){
			for(Fund fund:fundList){
				map.put(fund.getId(), fund);
			}
		}
		return map;
	}
	
	@Override
	public List<Fund> queryByIdsList(List<Long> list) {
		List<Fund> fundList = fundMapper.queryByIdList(list);
		return fundList;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Fund> queryByCondition (FundDto dto){
		PageHelper.startPage(dto.getPageNum(), dto.getPageSize(), true);
		List<Fund> list = fundMapper.queryByCondition(dto);
		PageInfo pageInfo = new PageInfo(list);
		return pageInfo.getList();
	}
	
	@Override
	public List<Fund> queryPageByIntentionIds(List<Long> list,Date pushTime,Integer limit,Integer state){
		PageHelper.startPage(1, limit, true);
		List<Fund> page = fundMapper.queryByIntentionIds(list,pushTime,state);
		PageInfo pageInfo = new PageInfo(page);
		return pageInfo.getList();
	}

/*	@Override
	public PageInfo queryFundByFSearchDto(FundSearchDto dto,
			Integer page, Integer rows) {
		PageHelper.startPage(page, rows, true);
		List<FundSearchVo> list = fundMapper.queryFundByFSearchDto(dto);
		PageInfo pageInfo = new PageInfo(list);
		return pageInfo;
		
				dto.setUserId(users.getUid());
				dto.setOwner(users.getUid());
				dto.setStatusList(statusList);
				dto.setOperatorId(userback.getId());
	}*/
	
	@Override
	public PageInfo queryFundByFSearchDto(FundSearchDto dto,Map<String, Map<String, Object>> backUserMap,
			Integer page, Integer rows) {
		SolrHelper<Fund> solrHelper = new SolrHelper<Fund>(solrService.getSolrFundUrl());
		if(StringUtils.isNotBlank(dto.getIndustryId())){
			solrHelper.andLike("industryId", dto.getIndustryId());
		}

		if(null!=dto.getState()){
			solrHelper.andEquals("state",dto.getState().toString());
		}
		if(null!=dto.getDestination() && !"0".equals(dto.getDestination())){
			solrHelper.andLike("destination",dto.getDestination().toString() );
		}
		if(null!=dto.getInvestMode()){
			solrHelper.andEquals("investMode", dto.getInvestMode().toString());
		}
		if(null!=dto.getUserId()){
			solrHelper.andEquals("userId", dto.getUserId().toString());;
		}
       if(dto.getOperatorId() != null){
    	   solrHelper.andEquals("operatorId", dto.getOperatorId()+"");
       }
		if(null != dto.getStatusList()){
			List<Integer> stateInt = dto.getStatusList();
			String[] stateStr =new String[stateInt.size()];
			for (int i = 0; i < stateInt.size(); i++) {
					stateStr[i] = stateInt.get(i).toString();
			}

			solrHelper.andIn("state", stateStr);
		}
		if(null != dto.getStartTime()){
			solrHelper.andDateGreaterThan("pushTime", dto.getStartTime());
		}
		if(null != dto.getEndTime()){
			solrHelper.andDateLessThan("pushTime", dto.getEndTime());
		}
		if (StringUtils.isNotBlank(dto.getKeyword())) {
			solrHelper.andStartSub();
			List<String> list = userDao.findUidByRealNameOrUmobile(dto.getKeyword());
			if (CollectionUtils.isNotEmpty(list)) {
				solrHelper.orIn("userId", list);
			}
			solrHelper.orLike("titlesVal", dto.getKeyword());
			solrHelper.orLike("fundNo", dto.getKeyword());
			solrHelper.endSub();
		}
		
		List<Fund> fundList = solrHelper.execQuery(page, rows, "id desc", Fund.class);
		
		List<FundSearchVo> searchDto = new ArrayList<FundSearchVo>();
		if(CollectionUtils.isNotEmpty(fundList)){
			for (Fund fund : fundList) {
				FundSearchVo fundsearchDto = new FundSearchVo();
				try {
					BeanUtils.copyProperties(fundsearchDto,fund);
					searchDto.add(fundsearchDto);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		}	
		PageInfo pageInfo = new PageInfo(fundList);
		searchDto = buildData(searchDto,backUserMap);
		pageInfo.setList(searchDto);
		return pageInfo;

	}

	public  List<FundSearchVo> buildData(List<FundSearchVo> listVo,Map<String, Map<String, Object>> backUserMap){
		//Map<String, Map<String, Object>> backUserMap = backUserService.getBackUserMap();  //获取所有后台用户的map		
		if(null!=listVo && !"".equals(listVo) && listVo.size()>0){
			List<Long> intentionIds = new ArrayList<Long>();
			List<Long> ownerIds = new ArrayList<Long>();
			//第一步循环所有查询参数id
			for (FundSearchVo vo : listVo) {
				if(null!= vo.getIntention()){
					intentionIds.add(vo.getIntention());
				}
				if(null!=vo.getUserId()){
					ownerIds.add(vo.getUserId());
				}

			}

			List<Intention> intentionList =   intentionService.getIntentionList(intentionIds); 
			List<User> userList =   userService.findByUid(ownerIds);

			
			//第二部拼接数据
			for (FundSearchVo vo :listVo) {
				 //获取后台用户的名称
				  if(null!=vo.getOperatorId()){
						 vo.setOperatorNames(backUserMap.get(vo.getOperatorId().toString()).get("user_name").toString()); //操作人名称  
				  }
				  
				  //根据intention找出name
				  if(null!=vo.getIntention()){
					  for (Intention inten:intentionList) {
						if(vo.getIntention().longValue() ==  inten.getId().longValue()){
							vo.setIntentionName(inten.getIntro());
							break;
						}
					}
				  }
				  
				  //取出发布人的ID找名称和电话
				  if(null!=vo.getUserId()){
					  for(User user : userList){
						  if(vo.getUserId().longValue() == user.getUid().longValue()){
							  vo.setUserPhone(null!=user?user.getUmobile():"");
							  vo.setUserName(null!=user?user.getRealname():""); 
							  break;
						  }  
					  }
				  }
				  //取出投资行业
				  if(StringUtils.isNotBlank(vo.getIndustryId())){
					  List<Integer> listInt =new ArrayList<Integer>();
					  String[] str = vo.getIndustryId().split("#");
					  vo.setIndustryId(vo.getIndustryId().replaceAll("#", ","));
						for (int j = 0; j < str.length&&StringUtils.isNumeric(str[j]); j++) {
							listInt.add(Integer.valueOf(str[j]));
						} 
					if(null!=listInt && listInt.size()>0 && !"".equals(listInt)){
						List<Industry> listInd = 	industryService.selectIndustryByIds(listInt);
						  if(null!=listInd){
							  String val ="";
							  for (int k = 0; k < listInd.size(); k++) {
								   val= val+listInd.get(k).getIndustryName()+",";
								  vo.setIndustryName(val);
							}
						  }
					}	

				  }
				  //取出投资地区
				  if(StringUtils.isNotBlank(vo.getDestination())){
					  List<String> listStr =new ArrayList<String>();
					  String[] str = vo.getDestination().split("#");
					  vo.setDestination(vo.getDestination().replace("#", ","));
					  if(str.length==1 && "0".equals(str[0])){
						  vo.setDestinationName("全国");
					  }else{
							for (int j = 0; j < str.length; j++) {
								listStr.add(str[j]);
							}
						  List<CityInfo> cityList = cityInfoService.selectByListPostCode(listStr);
						  if(null!=cityList){
							  String val ="";
							  for (int k = 0; k < cityList.size(); k++) {
								  val = val+cityList.get(k).getCityName()+",";
								  vo.setDestinationName(val);
							}
						  }
					  }

				  }	
			}

			}
		
		return listVo;
	}
	

	
	@Override
	public boolean upageStatus(List<Long> ids, String status,Long operatorId) {
		boolean ret = true;
		try {
			if(("203").equals(status)){
				fundMapper.upageStatus(ids,status,operatorId,new Date());
				
			}else{
				fundMapper.upageStatus(ids,status,operatorId,null);
			}
			for(Long id:ids){
				solrService.synFund(id);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			ret = false;
		}	
		for (int i = 0; i < ids.size(); i++) {
			fundStatusNotify(ids.get(i));
		}
		//资金发布
		if(ret&&status.equals(ProjectStatusEnums.RELEASE.getCode().toString())){
			List<Fund> funds =fundMapper.queryByIdList(ids);	
			if(CollectionUtils.isNotEmpty(funds)){	
				//监听资金发布事件
				BizMonitorService bizMonitor = getBizMonitorService();
				for(Fund fund:funds){
					bizMonitor.FundFirstPublish(fund);
				}
			}		
			deleteCache(funds);
		}
		return ret;
	}
		
	

	private void deleteCache(List<Fund> funds) {
		if(CollectionUtils.isNotEmpty(funds)){
			for(Fund fund:funds){
				Long id = fund.getId();
				String key = ResourceMatchCacheManagerImpl.buildKey(id,ResourceMatchTypeEnum.FUND.getCode());
				logger.info("Fund publish,Try to delete cache in redis, fund id="+id);
				resourceMatchCacheManager.delete(key);
			}
		}		
	}

	public boolean  updateByPrimaryKeySelective( Fund record ){
		boolean ret = true;
		try {
			fundMapper.updateByPrimaryKeySelective(record);
			solrService.synFund(record.getId());
		} catch (Exception e) {
			e.printStackTrace();
			ret = false;
		}	
		if(ret && null!=record.getIntention() && record.getIntention().longValue()!=0){
			fundStatusNotify(record.getId());
		}
		return ret;
		
	}
	
	public boolean  insert( Fund record ){
		boolean ret = true;
		try {
			fundMapper.insertSelective(record);
			solrService.synFund(record.getId());
		} catch (Exception e) {
			e.printStackTrace();
			ret = false;
		}	
		return ret;
		
	}

	@Override
	public Fund findById(Long id) {
		return fundMapper.findById(id);
	}

	@Override
	public boolean deleteFund(List<Long> ids) {
		boolean ret = true;
		try {
			fundMapper.deleteFund(ids);
			for(Long id:ids){
				solrService.delFund(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret = false;
		}
		if(ret){
			for (int i = 0; i < ids.size(); i++) {
				fundStatusNotify(ids.get(i));
			}
		}
		return ret;
	}

	@Override
	public List<Fund> queryFundByFundNo(String fundNo,List<Long> ids) {
		return fundMapper.queryFundByFundNo(fundNo,ids);
	}

	@Override
	public int countAllUserFund(Long uid) {
		return this.fundMapper.countByUid(uid);
	}
	
	@Override
	public PhotoFundVo viewPhoto(Long id) {
		PhotoFundVo photoFundVo = new PhotoFundVo();
		photoFundVo.setFundId(id);
		FundSearchVo fund = fundMapper.findByFundId(id);
		 //取出投资地区
		  if(StringUtils.isNotBlank(fund.getDestination())){
			  List<String> listStr =new ArrayList<String>();
			  String[] str = fund.getDestination().split("#");
			  fund.setDestination(fund.getDestination().replace("#", ","));
			  if(str.length==1 && "0".equals(str[0])){
				  fund.setDestinationName("全国");
			  }else{
					for (int j = 0; j < str.length; j++) {
						listStr.add(str[j]);
					}
				  List<CityInfo> cityList = cityInfoService.selectByListPostCode(listStr);
				  if(null!=cityList){
					  String val ="";
					  for (int k = 0; k < cityList.size(); k++) {
						  val = val+cityList.get(k).getCityName()+",";
						  fund.setDestinationName(val);
					}
				  }
			  }

		  }	
		
		List<Photo> photoList = photoDao.getPhotoListByFundId(id);
		photoFundVo.setPhotoList(photoList);
		photoFundVo.setFund(fund);
		return photoFundVo;
	}
	
	@Override
	public List<FundSearchVo> findFundSearchVo (List<Long> list){
		List<FundSearchVo> listVo = new ArrayList<FundSearchVo>() ;
		if( !list.isEmpty()){
			List<FundSearchVo> queryByIdList = fundMapper.queryByIdListVo(list);
			for (FundSearchVo vo : queryByIdList) {
				//取出投资地区
				  if(StringUtils.isNotBlank(vo.getDestination())){
					  List<String> listStr =new ArrayList<String>();
					  String[] str = vo.getDestination().split("#");
					  vo.setDestination(vo.getDestination().replace("#", ","));
					  if(str.length==1 && "0".equals(str[0])){
						  vo.setDestinationName("全国");
					  }else{
							for (int j = 0; j < str.length; j++) {
								listStr.add(str[j]);
							}
						  List<CityInfo> cityList = cityInfoService.selectByListPostCode(listStr);
						  if(null!=cityList){
							  String val ="";
							  for (int k = 0; k < cityList.size(); k++) {
								  val = val+cityList.get(k).getCityName()+",";
								  vo.setDestinationName(val);
							}
						  }
					  }

				  }
				//取出投资行业
				  if(StringUtils.isNotBlank(vo.getIndustryId())){
					  List<Integer> listInt =new ArrayList<Integer>();
					  String[] str = vo.getIndustryId().split("#");
					  vo.setIndustryId(vo.getIndustryId().replaceAll("#", ","));
						for (int j = 0; j < str.length&&StringUtils.isNumeric(str[j]); j++) {
							listInt.add(Integer.valueOf(str[j]));
						} 
					if(null!=listInt && listInt.size()>0 && !"".equals(listInt)){
						List<Industry> listInd = 	industryService.selectIndustryByIds(listInt);
						  if(null!=listInd){
							  String val ="";
							  for (int k = 0; k < listInd.size(); k++) {
								   val= val+listInd.get(k).getIndustryName()+",";
								  vo.setIndustryName(val);
							}
						  }
					}	

				  }
				//取出投资方式
				  if( null!=(vo.getInvestMode())){
					  SysDictionary selectByCode = sysDictionaryService.getByCodeFromLocalCache(String.valueOf(vo.getInvestMode()));
					  vo.setInvestModeName(selectByCode.getItemName());
				  }
				//取出发布人的ID找名称和电话
				  if( null!=vo.getUserId()){
					  User user = userDao.findById(vo.getUserId());
					  if( null != user){
						  if( StringUtils.isNotBlank(user.getUname())){
							  vo.setUserName(user.getUname());
						  }
						  if(user.getUmobile() != null){
							  vo.setUserPhone(user.getUmobile());
						  }
					  }
					 
				  }
				 //资金状态
				  if( null!=vo.getState()){
					  SysDictionary selectByCode = sysDictionaryService.getByCodeFromLocalCache(String.valueOf(vo.getState()));
					  vo.setStateName(selectByCode.getItemName());
				  }
				//认证状态
				  if( null!=vo.getAuth()){
					  SysDictionary selectByCode = sysDictionaryService.getByCodeFromLocalCache(String.valueOf(vo.getAuth()));
					  vo.setAuthName(selectByCode.getItemName());
				  }
				  listVo.add(vo);
			}
		}
		return listVo;
	}
	
	private BizMonitorService getBizMonitorService() throws BeansException { 
        return (BizMonitorService) SpringContextUtil.getBean("bizMonitorService"); 
	} 

	@Override
	public boolean updateStatus(Long id, String status, Long operatorId) {
		boolean ret = true;
		Fund funds=fundMapper.findById(id);	
		try {
			if(("203").equals(status)){
				if(null!=funds.getFristPushTime()){
					fundMapper.updateStatus(id,status,operatorId,null,new Date());
				}else{
					fundMapper.updateStatus(id,status,operatorId,new Date(),new Date());
				}
			}else{
				fundMapper.updateStatus(id,status,operatorId,null,null);
			}
	
				solrService.synFund(id);

			
		} catch (Exception e) {
			e.printStackTrace();
			ret = false;
		}	
	
			fundStatusNotify(id);

			//资金发布
			if(ret&&status.equals(ProjectStatusEnums.RELEASE.getCode().toString())){
				
				
				List<Fund> fundList = new ArrayList<Fund>();
				fundList.add(funds);
				if(CollectionUtils.isNotEmpty(fundList)){	
					//监听资金发布事件
					BizMonitorService bizMonitor = getBizMonitorService();
					for(Fund fund:fundList){
						bizMonitor.FundFirstPublish(fund);
					}
				}		
				deleteCache(fundList);
			}
		return ret;
	}
}
